package com.qys.livesMall.anchor.scheduledTask;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qys.livesMall.anchor.mapper.AnchorLivesSessionMapper;
import com.qys.livesMall.anchor.model.entity.AnchorLivesSession;
import com.qys.livesMall.anchor.model.entity.AnchorStatisticsTask;
import com.qys.livesMall.anchor.model.entity.H2Anchor;
import com.qys.livesMall.anchor.service.AnchorStatisticsTaskService;
import com.qys.livesMall.anchor.service.H2AnchorService;
import com.qys.livesMall.app.user.model.entity.AppUserConcern;
import com.qys.livesMall.app.user.service.AppUserConcernService;
import com.qys.livesMall.common.utils.DateUtils;
import com.qys.livesMall.shop.modal.vo.OrderAnchorListVO;
import com.qys.livesMall.shop.modal.vo.OrderFansRepurchaseVO;
import com.qys.livesMall.shop.service.ShopOrderSkuService;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class OrderAnchorStatisticsTask {
    @Resource
    private ShopOrderSkuService orderSkuService;
    @Resource
    private AppUserConcernService userConcernService;
    @Resource
    private H2AnchorService h2AnchorService;
    @Resource
    private AnchorStatisticsTaskService anchorStatisticsTaskService;
    @Resource
    private AnchorLivesSessionMapper anchorLivesSessionMapper;

    @Async
    @Scheduled(cron = "0 0 0 1/1 * ? ") // 每天晚上0点执行一次
    public void getOrderAnchorStatistics(){
        List<AnchorStatisticsTask> anchorStatisticsTasks=new ArrayList<>();
        List<H2Anchor> h2Anchors= h2AnchorService.getALl();
        //查询订单数据
        DateTime dateTime=DateUtils.yesterday();
        List<OrderAnchorListVO> shopOrderSkus=orderSkuService.getOrderAnchorList(null);
        //全部粉丝
        List<AppUserConcern> allFans=userConcernService.getUserConcernList(null);
        Map<Long,List<AppUserConcern>> mapAllFans = allFans.stream().collect(Collectors.groupingBy(a->a.getConcernId()));
        Map<Long,List<OrderAnchorListVO>> ShopOrderSkuMap=shopOrderSkus.stream().collect(Collectors.groupingBy(a->a.getAnchorId()));
        //查询全部主播粉丝复购率
        List<OrderFansRepurchaseVO> orderFansRepurchaseVOS = orderSkuService.getFansRepurchase();
        Map<Long,OrderFansRepurchaseVO> maporderFansRepurchase = orderFansRepurchaseVOS.stream().collect(Collectors.toMap(OrderFansRepurchaseVO::getAnchorId,a->a));
        for (H2Anchor anchor:h2Anchors){
            //主播ID
            Long anchorId=anchor.getId();
            //主播用户ID
            Long userId=anchor.getUserId();
            //粉丝信息
            List<AppUserConcern> allConcerns=mapAllFans.get(userId);
            //获取主播成交订单商品
            List<OrderAnchorListVO> anchorShopOrderSkus=ShopOrderSkuMap.get(anchorId);

            //累计粉丝数量
            AnchorStatisticsTask task0=new AnchorStatisticsTask();
            task0.setAnchorId(anchorId);
            task0.setStatisticalTime(dateTime.toLocalDateTime());
            task0.setNum(CollectionUtils.isEmpty(allConcerns)?"0":String.valueOf(allConcerns.size()));
            task0.setType("ljxzfs");
            anchorStatisticsTasks.add(task0);

            //成交订单数量
            AnchorStatisticsTask task=new AnchorStatisticsTask();
            task.setAnchorId(anchorId);
            task.setStatisticalTime(dateTime.toLocalDateTime());
            task.setNum(CollectionUtils.isEmpty(anchorShopOrderSkus)?"0":String.valueOf(anchorShopOrderSkus.size()));
            task.setType("ljcjdd");
            anchorStatisticsTasks.add(task);

            //成交人数
            List<OrderAnchorListVO> peopleAnchorShopOrderSkus =null;
            if (null != anchorShopOrderSkus){
                peopleAnchorShopOrderSkus = anchorShopOrderSkus.stream().collect(Collectors.
                        collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(OrderAnchorListVO::getUserId))), ArrayList::new));
            }
            AnchorStatisticsTask task2=new AnchorStatisticsTask();
            task2.setAnchorId(anchorId);
            task2.setStatisticalTime(dateTime.toLocalDateTime());
            task2.setNum(CollectionUtils.isEmpty(peopleAnchorShopOrderSkus)?"0":String.valueOf(peopleAnchorShopOrderSkus.size()));
            task2.setType("ljcjrs");
            anchorStatisticsTasks.add(task2);

            //成交转化率
            AnchorStatisticsTask task3=new AnchorStatisticsTask();
            task3.setAnchorId(anchorId);
            task3.setStatisticalTime(dateTime.toLocalDateTime());
            task3.setNum(convertFans(allConcerns,peopleAnchorShopOrderSkus));
            task3.setType("cjzhl");
            anchorStatisticsTasks.add(task3);

            //成交粉丝占比
            AnchorStatisticsTask task4=new AnchorStatisticsTask();
            task4.setAnchorId(anchorId);
            task4.setStatisticalTime(dateTime.toLocalDateTime());
            if (null != allConcerns && CollectionUtils.isNotEmpty(anchorShopOrderSkus)){
                List<Long> ids=allConcerns.stream().map(AppUserConcern::getUserId).collect(Collectors.toList());
                List<OrderAnchorListVO> fansPurchase=anchorShopOrderSkus.stream().filter(a->ids.contains(a.getUserId())).collect(Collectors.toList());
                task4.setNum(count(fansPurchase.size(),anchorShopOrderSkus.size()));
            }else {
                task4.setNum("0.00%");
            }
            task4.setType("cjfszb");
            anchorStatisticsTasks.add(task4);

            //粉丝复购率
            OrderFansRepurchaseVO orderFansRepurchaseVO = maporderFansRepurchase.get(anchorId);
            AnchorStatisticsTask task5=new AnchorStatisticsTask();
            task5.setAnchorId(anchorId);
            task5.setStatisticalTime(dateTime.toLocalDateTime());
            task5.setNum(orderFansRepurchaseVO==null?"0.00%":orderFansRepurchaseVO.getRepurchase());
            task5.setType("fsfgl");
            anchorStatisticsTasks.add(task5);

            //单场最高人数
            AnchorLivesSession livesSession = anchorLivesSessionMapper.selectOne(Wrappers.<AnchorLivesSession>lambdaQuery()
                    .select(AnchorLivesSession::getViewsNumber)
                    .eq(AnchorLivesSession::getAnchorId, anchorId)
                    .eq(AnchorLivesSession::getLivesStatus, 3)
                    .orderByDesc(AnchorLivesSession::getViewsNumber)
                    .last("limit 1"));
            AnchorStatisticsTask taskForSession = new AnchorStatisticsTask();
            taskForSession.setType("dczgrs");
            taskForSession.setNum(livesSession == null ? "0" : String.valueOf(livesSession.getViewsNumber()));
            taskForSession.setStatisticalTime(dateTime.toLocalDateTime());
            taskForSession.setAnchorId(anchorId);
            anchorStatisticsTasks.add(taskForSession);

            //累计观看人数
            AnchorLivesSession livesSessionForSum = anchorLivesSessionMapper.selectOne(Wrappers.<AnchorLivesSession>query()
                    .select("sum(views_number) as viewsNumber")
                    .eq("lives_status", 3)
                    .eq("anchor_id", anchorId));
            AnchorStatisticsTask taskForTotal = new AnchorStatisticsTask();
            taskForTotal.setType("ljgkrs");
            taskForTotal.setNum(livesSessionForSum == null ? "0" : String.valueOf(livesSessionForSum.getViewsNumber()));
            taskForTotal.setStatisticalTime(dateTime.toLocalDateTime());
            taskForTotal.setAnchorId(anchorId);
            anchorStatisticsTasks.add(taskForTotal);

        }
        //保存
        anchorStatisticsTaskService.saveBatch(anchorStatisticsTasks);
    }

    public String convertFans(List<AppUserConcern> appUserConcerns,List<OrderAnchorListVO> anchorShopOrderSkus){
        if (CollectionUtils.isEmpty(anchorShopOrderSkus) || CollectionUtils.isEmpty(appUserConcerns)){
            return "0.00%";
        }
        return count(appUserConcerns.size(),anchorShopOrderSkus.size());
    }
    public String count(int a , int b){
        //首先判断分母不能为0
        if(b!=0){
            float num = (float) a*100/b;
            DecimalFormat df = new DecimalFormat("0.00");//格式化小数 ， 其实这里还可以这样写 DecimalFormat("0.00%");   这样就不用在最后输出时还要加。
           return df.format(num);
        }
        return "0.00%";
    }
}
